<template>
  <div class="app-container" v-loading="loading">
    <el-backtop visibility-height="10"></el-backtop>
    <el-row class="title-row" :gutter="10">
      <el-col :span="1.5">
        <el-button plain icon="el-icon-back" size="small"  @click="cancel">取消</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="small" @click="saveNewsDraft">保存草稿</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-s-promotion" size="small" @click="issueNews">发布</el-button>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-row type="flex" :gutter="20">
          <el-col :span="10">
            <el-form-item label="封面图" prop="title_picture">
                <el-upload
                  ref="title-photo"
                  class="avatar-uploader"
                  :action="'/adminSever/newsBg/title-photo/' + articleId"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleUploadTitlePhotoSuccess"
                  :on-error="handleUploadTitlePhotoError"
                  :before-upload="beforeUploadTitlePhoto">
                  <el-image v-if="form.title_picture" :fit="'contain'" :src="form.title_picture" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="标题" prop="title">
              <el-input type="text" v-model="form.title" maxlength="40" show-word-limit />
            </el-form-item>
            <el-form-item label="副标题" prop="sub_title">
              <el-input type="textarea" v-model="form.sub_title" maxlength="150" :autosize="{ minRows: 4, maxRows: 4}" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容" prop="content">
          <v-md-editor v-model="form.content"
                       :disabled-menus="[]"
                       @upload-image="handleUploadImage"
          ></v-md-editor>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>

import { getToken } from '@/utils/auth'
import axios from 'axios'

export default {
  name: 'save-news',
  data() {
    return {
      loading: false,
      articleId: "",
      server: window.application.minio_host,
      form: {
        title: "",
        sub_title: "",
        content: "",
        title_picture: ""
      },
      headers: {
        token: getToken()
      },
      rules: {
        title: [
          { required: true, message: '新闻标题不能为空', trigger: ['blur', 'change'] },
          { min: 10, max: 40, message: '新闻标题长度必须介于 10 和 40 之间', trigger: ['blur', 'change'] }
        ],
        sub_title: [
          { required: true, message: '新闻副标题不能为空', trigger: ['blur', 'change'] },
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: ['blur', 'change'] },
        ],
        title_picture: [
          { required: true, message: '封面不能为空', trigger: ['blur', 'change'] },
        ]
      }
    }
  },
  created() {
    this.articleId = this.$route.query.id
    if (this.articleId === "") {
      this.$router.go(-1)
      this.$message.error("新闻编号为空不允许编辑！")
    }
  },
  mounted() {
    this.getNewsInfoById()
  },
  methods: {
    getNewsInfoById() {
      this.loading = true
      this.$store.dispatch("news/getNewsInfoById", this.articleId)
        .then((resp) => {
          this.form = resp.data.data
          this.form.title_picture = this.server + resp.data.data.title_picture
          this.$refs.form.resetFields();
        }).catch((error) => {
        this.$router.go(-1)
        this.$message.error(error)
      }).finally(() => {
        setTimeout(() => {
          this.loading = false
        },1500)
      })
    },
    cancel() {
      this.$confirm('此操作不会保留已输入信息 是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.$router.go(-1)
      }).catch(() => {})
    },
    saveNewsDraft() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$confirm('保存草稿不会将该新闻设置成发布状态，是否继续', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: "warning"
          }).then(() => {
            this.form.is_deleted = 1
            this.$store.dispatch("news/saveNewsInfo", this.form)
              .then((resp) => {
                if (resp) {
                  this.$message.success("保存草稿成功！")
                  this.getNewsInfoById()
                }
              })
              .catch((error) => {
                this.$message.error(error)
              })
          }).catch(() => {})
        }
      })
    },
    issueNews() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$confirm('是否发布该新闻? 不发布则点击保存草稿即可', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: "warning"
          }).then(() => {
            this.form.is_deleted = 0
            this.$store.dispatch("news/saveNewsInfo", this.form)
              .then((resp) => {
                if (resp) {
                  this.$message.success("发布成功！ 两秒内返回列表界面")
                  setTimeout(() => {
                    this.$router.push("news")
                  },2000)
                }
              })
              .catch((error) => {
                this.$message.error(error)
              })
          }).catch(() => {})
        }
      })
    },
    handleUploadTitlePhotoSuccess(response) {
      if (response.code === 1) {
        this.form.title_picture = this.server + response.data
      } else if( response.code === 0) {
        this.$message.error(response.msg)
      }
      this.$refs['title-photo'].clearFiles();
    },
    handleUploadTitlePhotoError(response) {
      this.$message.error(response.msg)
      this.$refs['title-photo'].clearFiles();
    },
    beforeUploadTitlePhoto(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG, PNG 格式!');
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
        return false
      }
      return isJPG && isLt2M;
    },
    // v-md-editor 文件上传
    handleUploadImage(event, insertImage, files) {
      let file = files[0]
      let formData = new FormData()
      formData.append("file", file)

      axios.post(`/adminSever/newsBg/content-photo/${this.articleId}`, formData, {
        headers: {
          token: getToken(),
        },
        'Content-Type': 'multipart/form-data'
      })
        .then((resp) => {
          if (resp.data.code === 1) {
            this.$notify({
              title: '提示',
              message: "需要控制图片大小时，在链接后添加'{{{width=\"宽度\" height=\"高度\"}}}' 即可控制",
              offset: 150,
              duration: 0
            });
            insertImage({
              url: this.returnUrl(resp.data.data),
              desc: resp.data.data.file_name
            });
          }
        })
        .catch((error) => {
          this.$message.error(error)
        })
    },
    returnUrl(data) {
      return this.server + data.bucket + "/" + data.url
    }
  },
  // 添加这一行 可以保证组件不被keep-alive进行缓存
  deactivated() {
    this.$destroy();
  }
}

</script>

<style scoped lang="scss">

.title-row {
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 500px;
  height: 200px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}

.avatar {
  width: 500px;
  height: 200px;
  display: block;
}

</style>
